package com.rc.evcharger.controller;

import com.rc.evcharger.biz.notify.NotifyStopChargeResult;
import com.rc.evcharger.common.base.TResponse;
import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.model.member.MemberInfo;
import com.rc.evcharger.model.member.MemberInfoExample;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.redis.RedChargeDataService;
import com.rc.evcharger.redis.RedPile;
import com.rc.evcharger.redis.RedisService;
import com.rc.evcharger.service.OrderCostService;
import com.rc.evcharger.service.elec.ElecGunService;
import com.rc.evcharger.service.elec.ElecPileService;
import com.rc.evcharger.service.hlhtsk.HlhtskTenantService;
import com.rc.evcharger.service.member.MemberAccountRecordService;
import com.rc.evcharger.service.member.MemberInfoService;
import com.rc.evcharger.service.order.OrderInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 结算当前数据;
 *
 * @author yang
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    protected RedisTemplate redisTemplate;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderCostService orderCostService;

    @Autowired
    private NotifyStopChargeResult notifyStopChargeResult;

    @Autowired
    private RedChargeDataService redChargeDataService;

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private MemberInfoService memberInfoService;

    /**
     * 后台结算订单（补推），跟updateOrderCostHlht1完全一样，不带密钥验证
     */
    @ResponseBody
    @RequestMapping(value = "/updateOrder", method = {RequestMethod.POST, RequestMethod.GET})
    public TResponse updateOrder(@RequestParam("orderId") Long orderId) {
        logger.info("后台结算订单（补推）,订单ID:{}", orderId);

        if (orderId == null) {
            return TResponse.FAIL("订单ID不能为空");
        }
        OrderInfo orderInfo = orderInfoService.selectByPrimaryKey(orderId);
        if (orderInfo == null) {
            return TResponse.FAIL("找不到对应订单,订单ID:{}" + orderId);
        }

        if ("5".equals(orderInfo.getStatus())) {
            return TResponse.FAIL("订单占位中,需要拔枪结算！");
        }

        logger.warn("订单结算接口被调用，订单ID为:{},订单状态:{}", orderId, orderInfo.getStatus());

        try {

            ElecGun elecGun = elecGunService.selectByPrimaryKey(orderInfo.getElecGunId());

            ElecPile elecPile = elecPileService.selectByPrimaryKey(orderInfo.getElecPileId());
            MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(orderInfo.getMemberId());

            //记录停止方式
            redChargeDataService.putStopMode(elecPile.getPileRtua(), elecGun.getGunNum(), memberInfo.getMobile(), SocketConstant.STOP_TENANT_0X1);
            //结算订单
            orderCostService.updateOrderCost(orderInfo.getOrderNum(), SocketConstant.STOP_ELELPILE_INTERNET_EXCEPTION_0x3);

            //推送订单停止状态,推送类型 0正常充电 1后台补推送 默认0
            notifyStopChargeResult.notifyOrderStop(orderInfo.getOrderNum(), SocketConstant.CON0, SocketConstant.CON1, 1);
        } catch (Exception e) {
            logger.error("订单结算接口异常", e);
        }

        TResponse tResponse = TResponse.SUCCESS();
        tResponse.put("订单完成结算");
        return tResponse;
    }


    /**
     * 后台结算订单（补推），跟updateOrderCostHlht1完全一样，不带密钥验证
     */
    @ResponseBody
    @RequestMapping(value = "/updateOrder/{mobile}", method = {RequestMethod.POST, RequestMethod.GET})
    public TResponse updateOrderByMemberId(@PathVariable("mobile") String mobile, String isUseGainAmount,String ticketIds,BigDecimal occupyAmount,String accountType) {
        logger.info("后台结算订单（补推）,订单ID:{},{},{},{}", mobile,isUseGainAmount,ticketIds,occupyAmount);

        if (mobile == null) {
            return TResponse.FAIL("手机号码不能为空");
        }

        MemberInfoExample memberInfoExample = new MemberInfoExample();
        memberInfoExample.createCriteria().andMobileEqualTo(mobile);

        List<MemberInfo> memberInfos = memberInfoService.selectByExample(memberInfoExample);
        MemberInfo memberInfo = memberInfos.get(0);

        OrderInfo orderInfo = orderInfoService.selectNewOrderByMemberId(memberInfo.getMemberId());


        if ("5".equals(orderInfo.getStatus())) {
            return TResponse.FAIL("订单占位中,需要拔枪结算！");
        }

        if ("1".equals(isUseGainAmount)){
            orderInfo.setIsUseGiveAmount("1");
        }else {
            orderInfo.setIsUseGiveAmount("0");
        }

        if (occupyAmount!=null){
            orderInfo.setOccupyAmount(occupyAmount);
        }
        if ("1".equals(accountType)){
            orderInfo.setAccountType("1");
        }else {
            orderInfo.setAccountType("0");
        }

        //充值优惠金额
        orderInfo.setDiscountAmount(BigDecimal.ZERO);
        orderInfo.setTicketAmount(BigDecimal.ZERO);
        orderInfo.setLevelDiscount(BigDecimal.ZERO);
        orderInfo.setGiveAmount(BigDecimal.ZERO);


        if (ticketIds!=null && !ticketIds.equals("")){
            orderInfo.setMemberTicketIds(ticketIds);
        }
        orderInfoService.updateByPrimaryKeySelective(orderInfo);

        logger.warn("订单结算接口被调用，订单ID为:{},订单状态:{}", orderInfo.getOrderId(), orderInfo.getStatus());

        try {

            ElecGun elecGun = elecGunService.selectByPrimaryKey(orderInfo.getElecGunId());

            ElecPile elecPile = elecPileService.selectByPrimaryKey(orderInfo.getElecPileId());

            //记录停止方式
            redChargeDataService.putStopMode(elecPile.getPileRtua(), elecGun.getGunNum(), memberInfo.getMobile(), SocketConstant.STOP_TENANT_0X1);
            //结算订单
            orderCostService.updateOrderCost(orderInfo.getOrderNum(), SocketConstant.STOP_ELELPILE_INTERNET_EXCEPTION_0x3);

            //推送订单停止状态,推送类型 0正常充电 1后台补推送 默认0
            notifyStopChargeResult.notifyOrderStop(orderInfo.getOrderNum(), SocketConstant.CON0, SocketConstant.CON1, 1);

            OrderInfo newOrderInfo = orderInfo;
            newOrderInfo.setOrderId(null);
            newOrderInfo.setStatus("6");
            newOrderInfo.setStartTime(new Date());
            newOrderInfo.setOrderNum(System.currentTimeMillis() + "1234");
            newOrderInfo.setOutOrderNum(System.currentTimeMillis() + "1234");
            newOrderInfo.setEndTime(new Date());

            newOrderInfo.setTotalPower(BigDecimal.TEN);
            newOrderInfo.setTotalSeviceMoney(BigDecimal.TEN);
            newOrderInfo.setTotalElecMoney(BigDecimal.TEN);
            newOrderInfo.setPayAmount(new BigDecimal(20));
            newOrderInfo.setTotalMoney(new BigDecimal(20));
            newOrderInfo.setDiscountAmount(BigDecimal.ZERO);
            //新增结算单
            orderInfoService.insertSelective(newOrderInfo);

        } catch (Exception e) {
            logger.error("订单结算接口异常", e);
        }

        TResponse tResponse = TResponse.SUCCESS();
        tResponse.put("订单完成结算");
        return tResponse;
    }

    /**
     * 充电中订单信息
     *
     * @return
     */
    @RequestMapping(value = "/chargeingOrder", method = RequestMethod.POST)
    public TResponse chargeingOrder() {
        HashMap<String, String> map = (HashMap<String, String>) redisTemplate.opsForHash().entries(RedPile.PILE);
        return TResponse.SUCCESS_DATA(map);
    }
}
